<?php


namespace app\index\controller;

use app\erp\controller\SendPhoneMsg;
use app\erp\model\OrderWarmdb;
use think\Db;
use think\worker\Server;
use Workerman\Lib\Timer;

class Worker extends Server
{
    protected $context = array(
        'ssl' => array(
            'local_cert' => '/www/wwwroot/dxtadmin/cert/ssl/fullchain.pem',
            'local_pk' => '/www/wwwroot/dxtadmin/cert/ssl/privkey.key',
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true, //如果是自签名证书需要开启此选项
        )
    );
    protected $transport = 'ssl';
    protected $option = array('lastMessageTime' => 0, 'transport' => 'ssl');

    public $name = 'juncai';

    public $socket = 'websocket://0.0.0.0:2346';
    public $heartbeat_time = 55;
    public $count = 1;
    public $processes = 1;// 只能是一个进程 否则Timer::add会多次执行


// 开启worker并初始化定时器
    public function onWorkerStart()
    {
        //print_r('开始工作\n');
        Timer::add(10, function () {
            // 获取配置文件
            $get_config = Db::name('site_config')
                ->whereIn('config_name', ['OPEN_ORDER_WARM', 'ORDER_WARM_PHONE', 'WARM_MINUTE'])
                ->field('config_name,config_value')
                ->column('config_value', 'config_name');
            if ($get_config['OPEN_ORDER_WARM'] == '开') {
                $last_time = Db::name('order')->order('order_id desc')->limit(1)->value('create_time');
                $time_now = time();
                $deff_time = $time_now - $last_time;
                $warm = false;
                if ($deff_time > $get_config['WARM_MINUTE'] * 60) {
                    // 30分钟内无订单
                    $warm = true;
                    // 验证并发送到手机
                    $orderWarmdb = new OrderWarmdb();
                    $get_last_time = $orderWarmdb->order('id desc')->value('create_time');
                    // 发送到手机号 每间隔30分钟发送
                    if (!$get_last_time || $time_now - $get_last_time > $get_config['WARM_MINUTE'] * 60) {
                        // 发送短信
                        $sendPhone = new SendPhoneMsg();
                        $msg_json = (object)[];
                        $result = $sendPhone->sendMsg($get_config['ORDER_WARM_PHONE'], 'SMS_467580436', $msg_json);

                        $save_data = [];
                        $save_data['phone'] = $get_config['ORDER_WARM_PHONE'];
                        $save_data['create_time'] = time();
                        $save_data['result'] = json_encode($result->body);
                        $orderWarmdb->save($save_data);
                    }
                }
                $this->broadcast(['type' => 'order_deff_time', 'warm' => $warm, 'deff_time' => $deff_time]);
            } else {
                $this->broadcast(['type' => 'order_deff_time', 'warm' => false, 'deff_time' => 0]);
            }

        });
        $this->worker->uidConnections = array();
        // 群发服务器时间
        // 通过心跳包验证是否在线
        Timer::add(55, function () {
            $time_now = time();
            //print_r(';心跳：' . $time_now);
            foreach ($this->worker->connections as $connection) {
                // 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
                if (!isset($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                }
                if ($time_now - $connection->lastMessageTime > $this->heartbeat_time) {
                    if (isset($connection->uid)) {
                        unset($this->worker->uidConnections[$connection->uid]);
                        $this->broadcast(['type' => 'offline', 'uid' => $connection->uid]);
                        unset($connection->uid);
                    }
                    $connection->close();
                }
            }
        });
    }

    // 监听消息
    public function onMessage($connection, $msg)
    {
        //print_r('收到消息');
        $data = json_decode($msg, true);
        $connection->lastMessageTime = time();
        if (!$data) {
            return;
        }
        if (!isset($data['type'])) {
            return;
        }
        switch ($data['type']) {
            case 'ping':
                // ping 同时绑定uid
                if (!isset($connection->uid) && isset($data['uid'])) {
                    $connection->uid = $data['uid'];
                    $connection->user_id = $data['user_id'];
                    $this->worker->uidConnections[$connection->uid] = $connection;
                    // 用户上线
                    $this->broadcast(['type' => 'online', 'uid' => $connection->uid]);
                }
                // 返回ping状态
                if (isset($data['uid'])) {
                    $send_msg = array(
                        'to_user_id' => $data['uid'],
                        'type' => 'ping'
                    );
                    $connection->send(json_encode($send_msg, JSON_UNESCAPED_UNICODE));
                }
                break;
            case 'single':
                // 单点聊天
                if (isset($connection->uid)) {
                    $send_msg = array(
                        'to_user_id' => $data['to_user_id'],
                        'from_user_id' => $data['from_user_id'],
                        'msg' => $data['msg'],
                        'msg_type' => $data['msg_type'],
                        'type' => 'single',
                        'room_id' => $data['room_id'] ?? 0
                    );
                    $msg_data = $this->createRoom($send_msg);
                    $msg_data['type'] = 'single';
                    $this->sendmsg($msg_data);
                }
                break;
        }

    }


    // 链接
    public function onConnect()
    {
        //print_r('链接:' . $this->worker->workerId);
    }

    // 关闭链接
    public function onClose($connection)
    {
        if (isset($connection->uid)) {
            // 群发离线消息
            unset($this->worker->uidConnections[$connection->uid]);
            $this->broadcast(['type' => 'offline', 'uid' => $connection->uid]);
            unset($connection->uid);
        }
    }

    // 群发推送消息
    protected function broadcast($msg)
    {
        $message = json_encode($msg, JSON_UNESCAPED_UNICODE);
        foreach ($this->worker->connections as $connection) {
            $connection->send($message);
        }
    }

    // 私聊
    protected function sendmsg($msg)
    {
        /*$message = json_encode($msg, JSON_UNESCAPED_UNICODE);
        // 这里是防止多点登录的情况，需要同步数据
        foreach ($this->worker->connections as $connection) {
            if (isset($connection->user_id)) {
                if ($connection->user_id == $msg['to_user_id']) {
                    $connection->send($message);
                }
                // 同时发送数据给发送者
                if ($connection->user_id == $msg['from_user_id']) {
                    $connection->send($message);
                }
            }
        }*/
    }
}